<?php
try{
    $db = new PDO('mysql:host=localhost;dbname=db2', 'root', '12qwas');
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    if($r=$_POST){
        if($_GET['xh']){//修改已经存在的记录
            $ps=$db->prepare('update students set xh=?, name=?, tel=? where xh=?');
            $ps->execute([$r['xh'],$r['name'],$r['tel'],$_GET['xh']]);
        }else{//注册新用户
            $ps=$db->prepare('insert into students (xh,name,tel) values (?,?,?)');
            $ps->execute([$r['xh'],$r['name'],$r['tel']]);
        }
        header('Location: index.php');
        return;
    }elseif($_GET['xh']) {
        $ps = $db->prepare("select * from students where xh=?");
        $ps->execute(array($_GET['xh']));
        $r = $ps->fetch();
        if ($r === false) throw new Exception('找不到要修改的记录~');
    }
}catch(Throwable $e){
    $msg=$e->getMessage();
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?=$_GET['xh']===null?'注册':'修改'?>新用户</title>
    <style>
        h1{ color:red;}
        input{ padding: 10px; margin:6px; border-radius: 6px;}
        .msg{ color:red; margin: 20px 0;}
    </style>
</head>
<body>
<h1><?=$_GET['xh']===null?'注册':'修改'?>新用户</h1>
<form method="post">
    学号：<input type="text" name="xh" value="<?=$r['xh']?>"><br>
    姓名：<input type="text" name="name" value="<?=$r['name']?>"><br>
    电话：<input type="text" name="tel" value="<?=$r['tel']?>"><br>
    <div class="msg"><?=$msg?></div>
    <input type="submit" value="提交数据">
</form>
</body>
</html>